<?php

namespace app\api\controller;

use app\api\model\wanlshop\Pay;
use app\common\Codes;
use app\common\controller\Api;
use think\Db;
use think\Exception;

class Task extends Api
{
    protected $noNeedLogin = ['percent_15','task_to_user'];


   //15%分红
   public function percent_15(){
        //查询某个时间
       $start_time = strtotime(date('Y-m-d',strtotime("-1 day")));
//       $start_time = strtotime(date('Y-m-d'));
       $end_time = $start_time+86399;
       $percent = 0.15;
       //获取销售额
       $payAmount = (new Pay())->where('createtime','>=',$start_time)
           ->where('createtime','<',$end_time)->where('pay_state',1)
           ->sum('total_amount');

       $moneyFormat = bcmul($payAmount,$percent,2);

       //查询所有有分红值的人
       $allGfScores = model('app\common\model\User')->where('gf_score','>',0)->sum('gf_score');
       $users = model('app\common\model\User')->where('gf_score','>',0)->select();
       $itemScore = bcdiv($moneyFormat,$allGfScores,2);
        $insert = [];
       //给TASK表先插入
       foreach ($users as $value){
            $insert[] = [
                'user_id'=>$value['id'],
                'item_score'=>bcmul($itemScore,$value['gf_score'],2),
                'status'=>0,
                'createtime'=>time()
            ];
       }

       if(!empty($insert)){
           model('app\common\model\UserScoreTask')->insertAll($insert);
       }
   }


   public function task_to_user(){
        $lists = model('app\common\model\UserScoreTask')->where('status',0)->select();
        foreach ($lists as $value){
            Db::startTrans();
            try {
            //增加消费券
                model('app\common\model\User')->money($value['item_score'],$value['user_id'],'分红奖励消费券');
                //增加分红值
                model('app\common\model\User')->gfscore(-($value['item_score']),$value['user_id'],'分红值扣除',0,0);

                model('app\common\model\UserScoreTask')->where('id',$value['id'])->update([
                    'status'=>1
                ]);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
            }
        }
   }


}